<template>

  <div id="app">
  <loading-global_1 v-show="loadingg"/>
</div>
  <div style="margin-top: 15px;display: flex">

    <div style="flex: 1;margin: auto">
      <strong>标题 :</strong>
    </div>
    <div style="max-width: 42.5vw;flex: 12;">
      <a-textarea
          v-model:value="title"
          placeholder="在此输入标题"
          auto-size
      />
    </div>
    <div style="flex: 10"/>
    <div style="flex: 3">
      <a-button type="primary" block @click="publish">发布</a-button>
      <a-modal
          v-model:visible="visible"
          title="发布文章"
          ok-text="发布"
          cancel-text="取消"
          @ok="onOk"
      >
        <a-form ref="formRef" :model="essay" layout="vertical" name="form_in_modal" >
          <a-form-item
              name="category"
              label="类别"
              :rules="[{ required: true, message: '选一个类别' }]"
              style="width: 200px"
          >
            <a-select
                v-model:value="essay.category"
                @dropdownVisibleChange="dropdownCategory"
                :loading="loadingO"
                :options="categoryOptions"
                :disabled="isCategoryDisabled"
                @change="isnull"
            ></a-select>
          </a-form-item>

          <a-space
              v-for="(item,index) in addCategory"
              :key="index"
              align="baseline">
            <a-form-item
                :name="index"

            >
              <a-input v-model:value="addCategory[index]" placeholder="输入新类别" />
            </a-form-item>
            <MinusCircleOutlined @click="removeCategory(item)" />
          </a-space>
          <a-form-item>
            <a-button type="dashed" @click="handleAddCategory" :disabled="isAddCategoryDisabled">
              <PlusOutlined />
              添加新类别
            </a-button>
          </a-form-item>

          <a-form-item
              name="labelList"
              label="标签"
              :rules="[{ required: true, message: '至少选一个标签' }]"
          >
            <a-select
                v-model:value="essay.labelList"
                mode="multiple"
                placeholder="先确定类别"
                @dropdownVisibleChange="dropdownLabel"
                :options="labelOptions"
                :loading="loadingL"
            ></a-select>
          </a-form-item>

          <a-space
              v-for="(item,index) in addLabel"
              :key="index"
              align="baseline">
            <a-form-item
                :name="index"

            >
              <a-input v-model:value="addLabel[index]" placeholder="输入新标签" />
            </a-form-item>
            <MinusCircleOutlined @click="removeLabel(item)" />
          </a-space>
          <a-form-item>
            <a-button type="dashed" @click="handleAddLabel">
              <PlusOutlined />
              添加新标签
            </a-button>
          </a-form-item>

        </a-form>
      </a-modal>
    </div>
  </div>

  <div style="margin-top: 10px">
<!--    <div v-if="uploading" >图片上传中...<a-spin/></div>-->
    <v-md-editor
        v-model="text"
        height="87vh"
        :disabled-menus="[]"
        @upload-image="handleUploadImage"
        @save="save"
        v-loading="uploading"
        @change="update"
    ></v-md-editor>

  </div>

</template>

<script setup>
import {onMounted, reactive, ref, watch} from "vue";
import {put} from "@/utils/OSS";
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue'
import {message,Input} from "ant-design-vue";
import request from "@/utils/request";
import {useStore} from "vuex";
import LoadingGlobal_1 from "@/components/utils/loadingGlobal_1";
import {useRouter,useRoute} from "vue-router";
import {debounce} from "lodash-es";

const store=useStore()
const router=useRouter()
const route=useRoute()

const loadingg=ref(false)
const uploading=ref(false)
const loadingO=ref(false)
const loadingL=ref(false)
const isCategoryDisabled=ref(false)
const isAddCategoryDisabled=ref(false)


const addCategory=ref([])
const addLabel=ref([])
const title=ref('')
const text = ref('');
const essay=reactive({
  title:title.value,
  content:text.value,
  category:'',
  labelList:[]
})

const visible = ref(false);
const formRef = ref();
const categoryOptions=ref([])
const labelOptions=ref([])


onMounted(()=>{

  if (route.params.title!==''){
    request.get("draft/get/"+route.params.title).then(res=>{
      console.log("draft  :",res)
      title.value=res.data.title
      text.value=res.data.content
    })
  }
})

function categoryToSelect(data) {
  let options=[]
  for (let item in data ){
    options.push({
      label:data[item],
      value:data[item]
    })
  }
  return options
}
function labelToSelect(data) {
  let options=[]
  for (let item in data ){
    options.push({
      label:data[item].label,
      value:data[item].label
    })
  }
  return options
}
function unique(arr){
  for(let i=0; i<arr.length; i++){
    for(let j=i+1; j<arr.length; j++){
      if(arr[i]===arr[j]){         //第一个等同于第二个，splice方法删除第二个
        arr.splice(j,1);
        j--;
      }
    }
  }
  return arr;
}
function isRepeat(){
  if (addLabel.value.length!==0){
    for (let x=0;x<addLabel.value.length-1;x++){
      if (addLabel.value[addLabel.value.length-1]===addLabel.value[x]){
        return true
      }
    }
    return addLabel.value[0] === '';

  }
}

const update = debounce((text) => {
  if(title.value==='')
    console.log("标题不能为空")
  else {
    request.post("draft/add",{title:title.value,content:text}).then(res=>{
      console.log("已存至草稿")
    })
  }
}, 5000)

watch(addCategory.value,(now)=>{
  // console.log("watch  :",now)
  essay.category=now[0]

})

const removeCategory = item => {
  let index = addCategory.value.indexOf(item);

  if (index !== -1) {
    addCategory.value.splice(index, 1);
    if (addCategory.value.length===0){
      isCategoryDisabled.value=false
      isAddCategoryDisabled.value=false
    }
  }
};

const handleAddCategory = () => {
  addCategory.value.push('')
  isCategoryDisabled.value=true
  isAddCategoryDisabled.value=true

};

const removeLabel = item => {
  let indexAddLabel = addLabel.value.indexOf(item);
  let indexLabelList=essay.labelList.indexOf(item)

  if (indexAddLabel !== -1) {
    addLabel.value.splice(indexAddLabel, 1);
    essay.labelList.splice(indexLabelList,1)
  }
};

const handleAddLabel = () => {

  if (addLabel.value[addLabel.value.length-1]==='')
    message.warning("新标签不能为空")
  else if (essay.category==='')
    message.warning("先选择类别")
  else if (isRepeat())
    message.warning("标签重复")
  else
    addLabel.value.push('')
};

const isnull=(v)=>{
  essay.labelList=[]
}

const dropdownCategory=(open)=>{
  if (open){
    loadingO.value=true
    request.get("category/getlist").then(res=>{
      console.log(res)
      categoryOptions.value=categoryToSelect(res.data)
      loadingO.value=false
    })
  }

}
const dropdownLabel=(open)=>{
  if (open){
    if (essay.category!=='')
    loadingL.value=true
    request.get("label/get/bycategory/"+essay.category).then(res=>{
      console.log(res)
      labelOptions.value=labelToSelect(res.data)
      loadingL.value=false
    })
  }
}

const publish = () => {
  if (title.value===''||text.value==='')
    message.warning("文章标题和文章内容不得为空")
  else
    visible.value=true
}

const onOk = () => {
  if (isRepeat()){
    message.warning("标签重复")
  }else {
    loadingg.value=true
    essay.title=title.value
    essay.content=text.value
    essay.labelList=unique(essay.labelList.concat(addLabel.value))
    formRef.value.validateFields().then(values => {
      // console.log('Received values of form: ', values);
      // console.log('essay: ', toRaw(essay));
      console.log("addCategory  :",addCategory.value)
      let resMessage=''
      if(addCategory.value.length>0){
        // essay.category=addCategory.value[0]
        request.post("category/admin/add",{category:essay.category}).then(res=>{
          console.log("addCategoryRes  :",res)
          resMessage+="类别添加"+res.message+","

          console.log("addLabel  :",addLabel.value)
          if (addLabel.value.length>0){
            request.post("label/admin/addSet",{category:essay.category,labelSet:addLabel.value}).then(res=>{
              console.log("addLabelRes  :",res)
              resMessage+=res.message
              if (res.status!==200){
                loadingg.value=false
                message.error("标签已存在")
              }

              else {
                console.log("essay  :",essay)
                request.post("essay/admin/add",essay).then(res=>{
                  console.log("essayRes  :",res)
                  loadingg.value=false
                  if (res.status===200){
                    visible.value = false;
                    router.push('/admin/essay/add/success/'+resMessage)
                  }
                  else
                    message.error(res.message)
                })
              }

            })
          }
        })
      }else
      if (addLabel.value.length>0){
        request.post("label/admin/addSet",{category:essay.category,labelSet:addLabel.value}).then(res=>{
          console.log("addLabelRes  :",res)
          essay.labelList.concat(addLabel.value)
          resMessage+=res.message

          if (res.status!==200){
            loadingg.value=false
            message.error("标签已存在")
          }

          else {
            console.log("essay  :",essay)
            request.post("essay/admin/add",essay).then(res=>{
              console.log("essayRes  :",res)
              loadingg.value=false
              if (res.status===200){
                visible.value = false;
                router.push('/admin/essay/add/success/'+resMessage)
              }
              else
                message.error(res.message)
            })
          }
        })
      }else {
        console.log("essay  :",essay)
        request.post("essay/admin/add",essay).then(res=>{
          console.log("essayRes  :",res)
          loadingg.value=false
          if (res.status===200){
            visible.value = false;
            router.push('/admin/essay/add/success')
          }

          else
            message.error(res.message)

        })
      }

      // formRef.value.resetFields();
      // console.log('reset formState: ', toRaw(essay));
    }).catch(info => {
      console.log('Validate Failed:', info);
    });
  }

};


const handleUploadImage=(event, insertImage, files)=>{
  uploading.value=true
  console.log(event, insertImage, files[0])
  // console.log(files[0].lastModified)
  put("essayImage/"+files[0].lastModified,files[0]).then(result=>{
    insertImage({
      url:result.url,
    })
    uploading.value=false
  })
}

const save=(text, html)=>{
  console.log(text)
  if(title.value==='')
    message.warning("标题不能为空")
  else {
    request.post("draft/add",{title:title.value,content:text}).then(res=>{
      console.log(res)
      message.success("已存至草稿")
    })
  }
}

</script>

<style>
#app {
  font-family: Helvetica, sans-serif;
  height: 100%;
}
</style>
